package client;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import model.Order;
import model.User;
import server.Server;
import view.ClientGUI;

public class ClientImpl extends UnicastRemoteObject implements Client {
	
	private static final long serialVersionUID = -3568605371186869830L;
	
	public static final String SERVER_ADDRESS = "rmi://localhost:12345/ServerImpl";
	public Server server;
	private User user;
	private ClientGUI cg;
	
	/**
	 * The only constructor for the client implementation
	 * @param cg
	 * @throws RemoteException
	 * @throws MalformedURLException
	 * @throws NotBoundException
	 */
	public ClientImpl(ClientGUI cg) throws RemoteException,
			MalformedURLException, NotBoundException {
		super();
		this.cg = cg;
		
		// get a reference on the remote object so we can use it later on
		server = (Server) Naming.lookup(SERVER_ADDRESS);
	}

	/** 
	 * RMI callback functionality to alert the user of registration
	 * @param u
	 * 		The User object
	 * @throws RemoteException
	 *
	 */
	public void alertRegistered(User u) throws RemoteException {
		this.user = u;
		// update the history pane
		cg.populate();
	}

	/** 
	 * Set's to user to a logged in status
	 * @param u
	 * 		The User object
	 * @throws RemoteException
	 *
	 */
	public void setLoggedIn(User u) throws RemoteException {
		this.user = u;
		cg.populate();
	}

	/** 
	 * RMI callback functionality to alert the user of purchase
	 * @param o
	 * 		The Order object
	 * @throws RemoteException
	 *
	 */
	public void alertPurchase(Order o) throws RemoteException {
		cg.alertPurchase(o);
	}

	
	/** 
	 * RMI callback functionality to alert the user of share being sold
	 * @param o
	 * 		The Order object
	 * @throws RemoteException
	 *
	 */
	public void alertSold(Order o) throws RemoteException {
		cg.alertSold(o);
	}

	/**
	 * Used to get the current user logged in
	 * @throws RemoteException
	 * @return User
	 * 		The 'User' which is currently logged in
	 */
	public User getUser() throws RemoteException {
		return user;
	}

	/**
	 * Gets the server reference
	 * @return Server
	 * 		The reference of the server created
	 */
	public Server getServer() {
		return server;
	}

}
